﻿using IRepository;
using IService.Blog;
using Microsoft.Extensions.Logging;
using Model;
using Newtonsoft.Json;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Service.Blog
{
    public class CommentService: ICommentService
    {
        readonly ILogger<CommentService> logger;
        readonly IBaseRepository baseRepository;
        public CommentService(ILogger<CommentService> _logger, IBaseRepository _baseRepository)
        {
            logger = _logger;
            baseRepository = _baseRepository;
        }

        #region Get

        /// <summary>
        /// 查询所有评论（分页）
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public async Task<MessageModel<string>> GetAllToPage(int offset, int limit)
        {
            try
            {
                PageInfoModel<BComment> pageList = await baseRepository.QueryPage<BComment>(offset, limit, "ID");
                PageInfoModel<object> list = new PageInfoModel<object>();
                list.DataCount = pageList.DataCount;
                list.PageSize = pageList.PageSize;
                list.PageCount = pageList.PageCount;
                list.Page = pageList.Page;
                list.Data = new List<object>();
                foreach (var item in pageList.Data)
                {
                    BUser fromUser = baseRepository.Query<BUser>(n => n.ID == item.FromUserID).Result.FirstOrDefault();
                    BUser toUser = baseRepository.Query<BUser>(n => n.ID == item.ToUserID).Result.FirstOrDefault();
                    list.Data.Add(new
                    {
                        id=item.ID,
                        articleID=item.ArticleID,
                        articleTitle = item.ArticleTitle,
                        from_username= fromUser.UserName,
                        to_username= toUser!=null?toUser.UserName:"",
                        content=item.Content,
                        pid=item.Pid,
                        createdAt = item.CreatedAt,
                        updatedAt = item.UpdatedAt
                    });
                }
                string result = JsonConvert.SerializeObject(list);

                return new MessageModel<string>()
                {
                    Code = 20000,
                    Data = result,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<string>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        /// <summary>
        /// 查询所有评论
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public async Task<MessageModel<List<BComment>>> GetAll()
        {
            try
            {
                List<BComment> result = await baseRepository.Query<BComment>();
                return new MessageModel<List<BComment>>()
                {
                    Code = 20000,
                    Data = result,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<List<BComment>>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        /// <summary>
        /// 根据条件表达式查询数据列表
        /// </summary>
        /// <param name="whereExpression">条件表达式</param>
        /// <returns>数据列表</returns>
        public async Task<MessageModel<List<BComment>>> GetByExpression<BComment>(Expression<Func<BComment, bool>> whereExpression)
        {
            try
            {
                List<BComment> result = await baseRepository.Query(whereExpression);
                //LogLock.OutLogFile("GetByExpression", JsonConvert.SerializeObject(whereExpression), JsonConvert.SerializeObject(result), true);//存入日志
                return new MessageModel<List<BComment>>()
                {
                    Code = 20000,
                    Data = result,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<List<BComment>>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }


        /// <summary>
        /// 查询评论按ID
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<MessageModel<BComment>> GetById(int id)
        {
            try
            {
                BComment result = await baseRepository.Query<BComment>(id);
                //LogLock.OutLogFile("GetById", JsonConvert.SerializeObject(id), JsonConvert.SerializeObject(result), true);//存入日志
                return new MessageModel<BComment>()
                {
                    Code = 20000,
                    Data = result,
                    Message = "添加成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<BComment>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }
        #endregion

        #region Post
        /// <summary>
        /// 添加评论
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public async Task<MessageModel<string>> Post(BComment parameter)
        {
            try
            {
                parameter.CreatedAt = DateTime.Now;
                parameter.ID = await baseRepository.Add(parameter);
                //LogLock.OutLogFile("Post", JsonConvert.SerializeObject(parameter), JsonConvert.SerializeObject(parameter), true);//存入日志
                return new MessageModel<string>()
                {
                    Code = 200,
                    Data = parameter.ID.ObjToString(),
                    Message = "添加成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<string>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        #endregion

        #region Put
        /// <summary>
        /// 修改评论
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public async Task<MessageModel<string>> Put(BComment parameter)
        {
            try
            {
                parameter.UpdatedAt = DateTime.Now;
                bool flag = await baseRepository.Update(parameter);
                if (flag)
                {
                    return new MessageModel<string>()
                    {
                        Code = 200,
                        Data = parameter.ID.ObjToString(),
                        Message = "修改成功",
                        Success = true
                    };
                }
                return new MessageModel<string>()
                {
                    Data = null,
                    Message = "修改失败",
                    Success = false
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<string>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }
        #endregion

        #region Delete
        /// <summary>
        /// 删除评论
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<MessageModel<bool>> DelById(int id)
        {
            try
            {
                bool flag = await baseRepository.DeleteById<BComment>(id);
                //LogLock.OutLogFile("DelById", JsonConvert.SerializeObject(id), JsonConvert.SerializeObject(flag), true);//存入日志
                return new MessageModel<bool>()
                {
                    Code = 200,
                    Data = flag,
                    Message = "删除成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<bool>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        #endregion
    }
}
